var util = require('../../utils/util.js');
import {
  SoundPlayer
} from "../../utils/soundPlayer.js";
var date_util = require('../../utils/date_util.js');
var api = require('../../config/api.js');
var user = require('../../services/user.js');
var base64 = require('../../utils/base64.js')
const QR = require('../../utils/wxqrcode.js');
var player = new SoundPlayer();
var app = getApp();
var qrcode;
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'

Page({
  data: {
    navigationBarTitle: '我的',
    navigationBarHeight,
    statusBarHeight: app.statusBarHeight + 'px',
    tabbar: {},
    isIphoneX: app.globalData.isIphoneX ? true : false,
    winHeight: 0,
    winWidth: 0,
    // 用户授权
    userInfo: app.globalData.userInfo,
    systemInfo: {},
    hasUserInfo: app.globalData.hasUserInfo,
    auth: app.globalData.auth,
    hasPhone: app.globalData.hasPhone,
    getUserInfoFail: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    memoryList: [],
    commonList: [],
    selectedFlag: [],
    hiddenShare: true,

    qrcode: '',

    //轮播相关
    faAutoplay: false,

    //音频、视频播放相关
    isPlay: false,

    flag: 0,
    iidex: 0,

    // 用户信息
    uuInfo: {},

    userStatis: null,
  },

  //
  onLoad: function(options) {
    wx.hideTabBar();
    app.editTabbar();
    var that = this;
    let userEncode = options.userObj
    let uEncode = decodeURIComponent(userEncode)
    let uuInfo = JSON.parse(base64.decode(uEncode))
    that.setData({
      uuInfo: uuInfo,
    })

    wx.showShareMenu({ // 要求小程序返回分享目标信息      
      withShareTicket: true
    });

    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          systemInfo: res,
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
          itemWidth: res.windowWidth * 0.4,
        });
      }
    });
    wx.hideShareMenu();
    
  },
  onMyevent: function(e) {
    this.setData({
      userInfo: e.detail.paramBtoA.userInfo,
      hasUserInfo: e.detail.paramBtoA.hasUserInfo,
      auth: e.detail.paramBtoA.auth,
      hasPhone: e.detail.paramBtoA.hasPhone,
    })
    if (this.data.auth && this.data.hasPhone) {
      this.GetStatis(); 
      this.GetMyBuy();
      this.GetMemory();
    }
  },

  onReady: function() {},
  onShow: function() {
    var that = this
    var tt = wx.getStorageSync('userInfo');
    if (tt) {
      this.setData({
        userInfo: tt,
        hasUserInfo: true,
        auth: true,
        hasPhone: app.globalData.hasPhone,
      })
    }


    that.auth = that.selectComponent("#auth");
    util.getScope('scope.userInfo').then(function(res) {
      if (res) {
        that.auth.hideAuth();
        that.setData({
          auth: true,
          userInfo: app.globalData.userInfo,
          hasUserInfo: app.globalData.hasUserInfo,
          hasPhone: app.globalData.hasPhone,
        });
        that.GetStatis(); 
        that.GetMyBuy();
        that.GetMemory();
      } else {
        that.auth.showAuth();
      }
    })

  },
  onHide: function() {},
  onUnload: function() {},
  
  backhome: function () {
    var that = this;
    wx.navigateBack({
      delta: 1
    })
  },

  GetStatis: function () {
    util.pututrequest(api.userStatis + '?userId=' + this.data.uuInfo.id, "GET").then(res => {
      if (res && res.code==200) {
        this.setData({
          userStatis: res.data
        })
      }
    })
  },
  //共同经历
  GetMyBuy: function() {
    util.pututrequest(api.commonActivityList + '?userId=' + this.data.uuInfo.id + '&page=1', "GET").then(res => {
      if (res && res.code==200) {
        var commonList = []
        var comList = res.data
        if (comList && comList.length > 0) {
          for (var item in comList) {
            var act = comList[item]['activity']            
            act.feelingCount = comList[item]['feelingCount']
            act.participateUserCount = comList[item]['participateUserCount']
            var begin = date_util.convertTime(act.beginTime);
            var end = date_util.convertTime(act.endTime);
            var title_str = act.name.length > 19 ? act.name.substr(0, 16) + '...' : act.name;
            act.begin = begin
            act.end = end
            act.title_str = title_str
            commonList.push(act)            
          }
        }
        this.setData({
          commonList: commonList
        })
        
      }
    })
  },
  //回忆
  GetMemory: function() {
    var that = this
    if (that.data.auth) {
      util.pututrequest(api.memoryList + '?userId=' + this.data.uuInfo.id, "GET").then(res => {
        if (res && res.code==200) {
          var k = 0;
          var acts = []
          var res_acts = res.data
          if (res_acts) {
            var tickets = res_acts.memoryGroups
            for (var item in tickets) {
              var one_act = {}
              one_act.key = tickets[item]['monthYear']
              one_act.value = tickets[item]['memories']
              acts.push(one_act)

            }
          }
          this.setData({
            memoryList: acts
          })

        }
      })
    }
  },
  // 展开折叠选择  
  changeToggle: function(e) {
    var index = e.currentTarget.dataset.index;

    if (this.data.selectedFlag[index]) {
      this.data.selectedFlag[index] = false;
    } else {
      this.data.selectedFlag[index] = true;
    }

    this.setData({
      selectedFlag: this.data.selectedFlag
    })
  },

  sharePic: function(e) {
    let index = e.currentTarget.dataset.index
    var act = this.data.commonList[index]
    util.pututrequest(api.shareActivity + '?uuid=' + act.uuid + '&type=ACTIVITY', 'GET').then(res => {
      if (res.success) {
        this.setData({
          hiddenShare: false,
          shareindex: index,
          sharepicurl: res.data.path
        })
      }
    })
  },
  close_share: function(e) {
    this.setData({
      hiddenShare: true
    })
  },
  saveNetPicToLocal: function() {
    var imgPath = this.data.sharepicurl
    wx.downloadFile({
      url: imgPath,
      success: function(res) {
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(data) {
            wx.showModal({
              title: '保存成功',
              content: '活动海报保存到相册成功',
              confirmText: "我知道了",
              showCancel: false,
            })
          },
          fail: function(err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              // console.log("当初用户拒绝，再次发起授权")
              wx.openSetting({
                success(settingdata) {
                  // console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    // console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                    wx.showToast({
                      title: '授权成功，继续保存',
                      icon: 'success',
                      duration: 2000
                    })
                  } else {
                    // console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                    wx.showToast({
                      title: '未授权，无法保存',
                      icon: 'success',
                      duration: 2000
                    })
                  }
                }
              })
            }
          },
          complete(res) {

          }
        })
      }
    })
  },
  onShareAppMessage: function(res) {
    var act = this.data.commonList[this.data.shareindex]
    if (res.from === 'button') { //页面内转发   menu 菜单转发

    }
    return {
      title: act.begin.monthOri + '-' + act.begin.dayOri + '•' + act.area + '\n' + act.title,
      desc: act.title,
      path: '/pages/detail/detail?uuid=' + act.uuid + '&source=app&commId=0&type=0',
      imageUrl: this.data.sharepicurl,
      success: function(res) { // 转发成功       
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        //可以获取群组信息
        if (this.data.systemInfo.platform == 'android' && (shareTickets.length > 0)) {
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function(res) {
              wx.showToast({
                title: "分享成功",
                duration: 2000
              });
            },
            fail: function() {
              wx.showToast({
                title: "分享失败",
                duration: 2000
              });
            }
          })
        }
        if (this.data.systemInfo.platform == 'ios' && (shareTickets.length > 0)) {
          wx.showToast({
            title: "分享成功",
            duration: 2000
          });
        }
      },
      fail: function(res) { // 转发失败        
        wx.showToast({
          title: "分享失败，请重新分享",
          duration: 2000
        });
      }
    }
  },

  shareActivity: function() { //1.2.0 处理转发 兼容性
    if (wx.canIUse) {
      if (wx.canIUse('button.open-type.share')) {
        return;
      }
    }
    wx.showModal({
      title: '提示',
      content: '当前微信版本过低，无法使用该功能，请点击右上角<转发>菜单进行分享。'
    });
  },
  //// 播放音频
  audioPlay: function(e) {
    var that = this,
      id = e.currentTarget.dataset.id,
      path = e.currentTarget.dataset.path,
      key = e.currentTarget.dataset.key,
      memoryList = that.data.memoryList;
    path = 'https://blcclb.com/' + path;

    for (var i = 0; i < memoryList.length; i++) {
      var one_act = memoryList[i]
      // 处理视频 音频 播放标记
      if (one_act.value && one_act.value.length > 0) {
        for (var iitem in one_act.value) {
          var oneact = one_act.value[iitem]
          if (oneact.comments && oneact.comments.length > 0) {
            var oneactcomments = oneact.comments;
            for (var iiitem in oneactcomments) {
              if (oneactcomments[iiitem].id == id) {
                oneactcomments[iiitem].isPlay = true;
                break;
              }

            }
          }
        }
      }
    }

    that.setData({
      memoryList: memoryList
    })
    player.play(path, () => {

    });
  },
  // 停止音频
  audioStop: function(e) {
    var that = this,
      id = e.currentTarget.dataset.id,
      key = e.currentTarget.dataset.key,
      path = e.currentTarget.dataset.path,
      memoryList = that.data.memoryList;
    path = 'https://blcclb.com/' + path;
    //切换显示状态
    for (var i = 0; i < memoryList.length; i++) {
      var one_act = memoryList[i]
      // 处理视频 音频 播放标记
      if (one_act.value && one_act.value.length > 0) {
        for (var iitem in one_act.value) {
          var oneact = one_act.value[iitem]
          if (oneact.comments && oneact.comments.length > 0) {
            var oneactcomments = oneact.comments;
            for (var iiitem in oneactcomments) {
              if (oneactcomments[iiitem].id == id) {
                oneactcomments[iiitem].isPlay = false;
                break;
              }

            }
          }
        }
      }
    }

    that.setData({
      memoryList: memoryList
    })
    player.stop()
  },

  goUpload: function(e) {
    var that = this;
    if (!that.data.isShowDate) {
      wx.navigateTo({
        url: '/pages/search/search',
        success: function() {},
        fail: function() {},
        complete: function() {}
      })
    }
  },

  gotoStrength: function (e) {
    wx.navigateTo({
      url: '/pages/strength/strength',
      success: function () { },
      fail: function () { },
      complete: function () { }
    })
  },
  onPullDownRefresh() {
    var that = this
    that.GetStatis();
    that.GetMyBuy();
    that.GetMemory();
    wx.stopPullDownRefresh();
  },


})